<template>
  <div class="app-container">

    <!-- 课程信息表单 TODO -->
    <!-- 课程信息表单 -->
    <el-form label-width="120px">

      <el-form-item label="课程标题">
        <el-input v-model="courseInfo.title" placeholder=" 示例：机器学习项目课：从基础到搭建项目视频课程。专业名称注意大小写"/>
      </el-form-item>
      <!-- 课程讲师 TODO -->
      <el-form-item label="课程讲师">
        <!-- 一级分类 -->
        <el-select
          v-model="courseInfo.teacherId"
          placeholder="请选择">
          <el-option
            v-for="teacher in teacherList"
            :key="teacher.id"
            :label="teacher.name"
            :value="teacher.id"/>
        </el-select>
      </el-form-item>
      <!-- 所属分类 TODO -->
      <!-- 所属分类：级联下拉列表 -->
      <el-form-item label="课程类别">
        <!-- 一级分类 -->
        <el-select
          v-model="courseInfo.subjectParentId"
          placeholder="请选择"
          @change="subjectChanged">
          <el-option
            v-for="subject in subjectList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>

        <!-- 二级分类 TODO -->
        <!-- 二级分类 -->
        <el-select v-model="courseInfo.subjectId" placeholder="请选择">
          <el-option
            v-for="subject in subjectLevelTwoList"
            :key="subject.id"
            :label="subject.title"
            :value="subject.id"/>
        </el-select>
      </el-form-item>
      <el-form-item label="总课时">
        <el-input-number :min="0" v-model="courseInfo.lessonNum" controls-position="right" placeholder="请填写课程的总课时数"/>
      </el-form-item>

      <!-- 课程简介 TODO -->
      <el-form-item>
        <tinymce :height="300" v-model="courseInfo.description"/>
      </el-form-item>

      <!-- 课程封面 TODO -->
      <el-form-item label="课程封面">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
          action = "http://127.0.0.1:8083/admin/aliyun/oss/upload?module=cover"
        >
          <img v-if="courseInfo.cover" :src="courseInfo.cover" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>

      <el-form-item label="课程价格">
        <el-input-number :min="0" v-model="courseInfo.price" controls-position="right" placeholder="免费课程请设置为0元"/> 元
      </el-form-item>
    </el-form>
    <div style="text-align:center">
      <el-button :disabled="saveBtnDisabled" type="primary" @click="saveData()">保存并下一步</el-button>
    </div>
  </div>
</template>

<script>
import courseApi from '@/api/course'
import teacherApi from '@/api/teacher'
import subjectApi from '@/api/subject'
import Tinymce from '@/components/Tinymce'
export default {
  components: { Tinymce },
  data() {
    return {
      saveBtnDisabled: false, // 按钮是否禁用
      courseInfo: {// 表单数据
        price: 0,
        lessonNum: 0,
        // 以下解决表单数据不全时insert语句非空校验
        teacherId: '',
        subjectId: '',
        subjectParentId: '',
        cover: '',
        description: ''
      },
      teacherList: [],
      searchObj: {}, // 查询条件,
      subjectList: [], // 一级分类列表
      subjectLevelTwoList: [] // 二级分类列表
    }
  },
  created() {
    console.log(this.$route.params.id)
    console.log(this.$parent.courseId)
    console.log(this.$parent.courseId)
    if (this.$parent.courseId || this.$route.params.id) { // 回显
      this.fetchCourseInfoById(this.$parent.courseId === null ? this.$route.params.id : this.$parent.courseId)
    } else {
      this.initSubjectList()
    }
    this.initTeacherList()
  },
  methods: {
    // 保存并下一步
    saveAndNext() {
      this.saveBtnDisabled = true
      this.$parent.active = 1
    },
    querySearch(queryString, cb) {
      teacherApi.listByKey({ 'key': queryString }).then(res => {
        this.restaurants = res.data.list
      })
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        var map = this.restaurants.map(function(item, index) {
          return { value: item.name }
        })
        console.log(map)
        cb(map)
      }, 3000 * Math.random())
    },
    subjectChanged(value) {
      this.subjectList.forEach(subject => {
        if (subject.id === value) {
          this.courseInfo.subjectId = ''
          this.subjectLevelTwoList = subject.children
        }
      })
    },
    // 初始化一级分类
    initSubjectList() {
      subjectApi.getNestedTreeList().then(response => {
        this.subjectList = response.data.items
      })
    },
    // 初始化讲师
    initTeacherList() {
      teacherApi.getTeachers().then(res => {
        this.teacherList = res.data.list
      })
    },
    // 回写url
    handleAvatarSuccess(res, file) {
      console.log(res)
      console.log(URL.createObjectURL(file.raw))
      this.courseInfo.cover = res.data.url
    },
    // 图片类型验证
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      this.courseInfo.cover = file
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 保存
    saveData() {
      if (!this.$parent.courseId && !this.$route.params.id) {
        courseApi.saveCourseInfo(this.courseInfo).then(response => {
          this.$message.success(response.message)
          this.$parent.courseId = response.data.courseId // 获取courseId
          this.$parent.active = 1// 下一步
        })
      } else {
        courseApi.editCourseInfo(this.courseInfo).then(response => {
          this.$message.success(response.message)
          this.$parent.courseId = response.data.courseId // 获取courseId
          this.$parent.active = 1// 下一步
        })
      }
    },
    fetchCourseInfoById(id) {
      courseApi.getCourseInfoById(id).then(response => {
        this.courseInfo = response.data.item
        this.searchObj.name = this.courseInfo.teacherId
        subjectApi.getNestedTreeList().then(response => {
          this.subjectList = response.data.items

          // 填充二级菜单：遍历一级菜单列表，
          this.subjectList.forEach(subject => {
            // 找到和courseInfo.subjectParentId一致的父类别记录
            if (subject.id === this.courseInfo.subjectParentId) {
              // 拿到当前类别下的子类别列表，将子类别列表填入二级下拉菜单列表
              this.subjectLevelTwoList = subject.children
            }
          })
        })
      })
    }
  }
}
</script>

<style scoped>
  .tinymce-container {
    position: relative;
    line-height: normal;
  }
</style>
